package com.szosen.jkzj.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.szosen.database.DBService;
import com.szosen.database.niaoye;
import com.szosen.database.tiwen;
import com.szosen.database.xindian;
import com.szosen.database.xuetang;
import com.szosen.database.xueya;
import com.szosen.database.xueyang;
import com.szosen.database.xuezhi;
import com.szosen.jkzj.R;
import com.szosen.util.BackGroundThread;
import com.szosen.util.FileSaveUtil;
import com.szosen.util.FileSaveUtilecg2;
import com.szosen.util.SharedpreferenceUtil;
import com.szosen.util.ThreeCloumAdpter;
import com.szosen.util.ToastTool;
import com.szosen.util.Tools;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 本地测量记录
 */
public class LocalRecord extends BaseActivity {
    private Context context;
    private ThreeCloumAdpter mAdapter;
    private ListView listview;
    private List<String[]> datas;
    private static final int[] ids = {R.id.show_ecg, R.id.show_bp,
            R.id.show_bo, R.id.show_temp, R.id.show_glu, R.id.show_urine};
    private static final int UPLOAD_RESULT = 0;
    private int lastPressBtnId = ids[1];
    private String[] title = {"测量时间", "测量值", "上传状态"};
    private static final int UPLOAD_ALL_RESULT_OK = 1222;
    private static final int UPLOAD_ALL_RESULT_MSG = 1265;
    private static final int UPLOAD_ALL_RESULT_NOKNOW_ERROR = 1267;
    private static final int UPLOAD_ALL_RESULT_ERROR = 1233;
    private static final int UPLOAD_ALL_NODATA = 1234;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.latest_measure);
        super.setTitleContent("测量记录");
        context = this;
        datas = new ArrayList<String[]>();
        mAdapter = new ThreeCloumAdpter(context, datas);
        listview = (ListView) findViewById(R.id.show_table_listview);
        listview.setAdapter(mAdapter);
        listview.setOnItemLongClickListener(longClickListener);
        // 设置点击的时候打印测量记录
        listview.setOnItemClickListener(itemClickListener);
        lastPressBtnId = R.id.show_bp;
        setButtonState(lastPressBtnId);
        switchSelect(lastPressBtnId);
    }

    public void finishActivity(View view) {
        onBackPressed();
    }

    /***
     * R.id.show_ecg, R.id.show_bp, R.id.show_bo, R.id.show_temp, R.id.show_glu,
     * R.id.show_urine
     *
     * @param view
     */
    public void uploadAllData(View view) {

    }

    /***
     * 上传一个表里面的所有未上传的数据。
     *
     * @param tableName
     */
    public void uploadTable(final String tableName) {
    }
    //刷新该选择的id的数据
    private static final int WHAT_REFRESHDATASELECT = 0x2;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switchSelect(lastPressBtnId);
        }
    };
    private OnItemLongClickListener longClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long id) {
            final String[] item = (String[]) parent.getAdapter().getItem(
                    position);
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
            dialogBuilder.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            deleteRecordByTime(item[0], lastPressBtnId);
                            try {
                                if (lastPressBtnId == R.id.show_ecg) {
                                    String pngPath = item[3];
                                    if (!TextUtils.isEmpty(pngPath)) {
                                        File file = new File(pngPath);
                                        if (file.exists()) {
                                            file.delete();
                                        }
                                    }
                                    String pngPathResult = item[3].substring(0, item[3].length() - 4) + "_结论.png";
                                    if (!TextUtils.isEmpty(pngPathResult)) {
                                        File file = new File(pngPathResult);
                                        if (file.exists()) {
                                            file.delete();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                System.out.println("删除心电记录的图片失败");
                            }
                        }
                    });
            dialogBuilder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            dialogBuilder.setCancelable(false);
            dialogBuilder.setTitle("提示").setMessage("你确定要删除这条测量记录吗?");
            AlertDialog dialog = dialogBuilder.create();
            dialog.show();
            return true;
        }

    };
    private OnItemClickListener itemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // 如果不是心电、不是尿液，就返回。不显示打印
            if (lastPressBtnId == R.id.show_temp || lastPressBtnId == R.id.show_xuezhi) {
                return;
            }
            final String[] item = (String[]) parent.getAdapter().getItem(
                    position);
            //获取时间time查询数据库。然后保存
            final String time = item[0];
            //血压
            if (lastPressBtnId == R.id.show_bp) {
                //修改血压测量的结果
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        context);
                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                TableLayout tl = (TableLayout) inflater.inflate(
                        R.layout.localrecord_xueya_edit_dialog, null);
                final EditText et_shuzhang = (EditText) tl
                        .findViewById(R.id.localrecord_xueya_editDialog_et_shuzhang);
                final EditText et_shousuo = (EditText) tl
                        .findViewById(R.id.localrecord_xueya_editDialog_et_shousuo);
                final EditText et_mailv = (EditText) tl
                        .findViewById(R.id.localrecord_xueya_editDialog_et_mailv);
                final List<Object> xueyas = (List<Object>) DBService.queryByKey(new xueya(time));
                xueya bean = null;
                if (xueyas != null && xueyas.size() > 0) {
                    bean = (xueya) xueyas.get(0);
                    et_shousuo.setText(bean.getSbp());
                    et_shuzhang.setText(bean.getDbp());
                    et_mailv.setText(bean.getPulse());
                }
                builder.setView(tl);
                builder.setTitle("填写您的血压");
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                String shousuoya = et_shousuo.getText().toString().trim();
                                String shuzhangya = et_shuzhang.getText().toString().trim();
                                String mailv = et_mailv.getText().toString().trim();
                                if (xueyas != null && xueyas.size() > 0) {
                                    xueya xy = (xueya) xueyas.get(0);
                                    xy.setDbp(shuzhangya);
                                    xy.setSbp(shousuoya);
                                    xy.setPulse(mailv);
                                    boolean b = DBService.add(xy);
                                    if (b) {
                                        ToastTool.showShort(context, "修改数据成功");
                                    }
                                    mHandler.obtainMessage(WHAT_REFRESHDATASELECT).sendToTarget();
                                }
                            }
                        });
                builder.setNegativeButton("取消", null);
                builder.create().show();
            } else if (lastPressBtnId == R.id.show_glu) {
                //修改血糖值
                //修改血压测量的结果
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        context);
                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                TableLayout tl = (TableLayout) inflater.inflate(
                        R.layout.localrecord_xuetang_edit_dialog, null);
                final EditText et_glu = (EditText) tl
                        .findViewById(R.id.localrecord_xuetang_editDialog_et_glu);
                final List<Object> xuetangs = (List<Object>) DBService.queryByKey(new xuetang(time));
                xuetang bean = null;
                if (xuetangs != null && xuetangs.size() > 0) {
                    bean = (xuetang) xuetangs.get(0);
                    et_glu.setText(bean.getGlu());
                }
                builder.setView(tl);
                builder.setTitle("修改血糖值:");
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                String glu = et_glu.getText().toString().trim();
                                if (xuetangs != null && xuetangs.size() > 0) {
                                    xuetang xt = (xuetang) xuetangs.get(0);
                                    xt.setGlu(glu);
                                    boolean b = DBService.add(xt);
                                    if (b) {
                                        ToastTool.showShort(context, "修改数据成功");
                                    }
                                    mHandler.obtainMessage(WHAT_REFRESHDATASELECT).sendToTarget();
                                }
                            }
                        });
                builder.setNegativeButton("取消", null);
                builder.create().show();
            } else if (lastPressBtnId == R.id.show_urine) {
                //如果是尿液。需要有打印、修改数据功能
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        context);
                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                TableLayout tl = (TableLayout) inflater.inflate(
                        R.layout.localrecord_niaoye_edit_dialog, null);
                final EditText leuEditText = (EditText) tl.findViewById(R.id.leu);
                final EditText nitEditText = (EditText) tl.findViewById(R.id.nit);
                final EditText ubgEditText = (EditText) tl.findViewById(R.id.ubg);
                final EditText proEditText = (EditText) tl.findViewById(R.id.pro);
                final EditText phEditText = (EditText) tl.findViewById(R.id.pH);
                final EditText sgEditText = (EditText) tl.findViewById(R.id.sg);
                final EditText bldEditText = (EditText) tl.findViewById(R.id.bld);
                final EditText ketEditText = (EditText) tl.findViewById(R.id.ket);
                final EditText bilEditText = (EditText) tl.findViewById(R.id.bil);
                final EditText gluEditText = (EditText) tl.findViewById(R.id.glu);
                final EditText vcEditText = (EditText) tl.findViewById(R.id.vc);

                final List<Object> niaoyes = (List<Object>) DBService.queryByKey(new niaoye(time));
                niaoye bean = null;
                if (niaoyes != null && niaoyes.size() > 0) {
                    bean = (niaoye) niaoyes.get(0);
                    leuEditText.setText(bean.getLeu());
                    nitEditText.setText(bean.getNit());
                    ubgEditText.setText(bean.getUbg());
                    proEditText.setText(bean.getPro());
                    phEditText.setText(bean.getPh());
                    sgEditText.setText(bean.getSg());
                    bldEditText.setText(bean.getBld());
                    ketEditText.setText(bean.getKet());
                    bilEditText.setText(bean.getBil());
                    gluEditText.setText(bean.getGlu());
                    vcEditText.setText(bean.getVc());
                }
                builder.setView(tl);
                builder.setTitle("修改尿液分析结果:");
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (niaoyes != null && niaoyes.size() > 0) {
                                    niaoye ny = (niaoye) niaoyes.get(0);
                                    ny.setLeu(leuEditText.getText().toString().trim());
                                    ny.setNit(nitEditText.getText().toString().trim());
                                    ny.setUbg(ubgEditText.getText().toString().trim());
                                    ny.setPro(proEditText.getText().toString().trim());
                                    ny.setPh(phEditText.getText().toString().trim());
                                    ny.setSg(sgEditText.getText().toString().trim());
                                    ny.setBld(bldEditText.getText().toString().trim());
                                    ny.setKet(ketEditText.getText().toString().trim());
                                    ny.setBil(bilEditText.getText().toString().trim());
                                    ny.setGlu(gluEditText.getText().toString().trim());
                                    ny.setVc(vcEditText.getText().toString().trim());
                                    boolean b = DBService.add(ny);
                                    if (b) {
                                        ToastTool.showShort(context, "修改数据成功");
                                    }
                                    mHandler.obtainMessage(WHAT_REFRESHDATASELECT).sendToTarget();
                                }
                            }
                        });
                builder.setNeutralButton("打印",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                printTable(item, lastPressBtnId);
                            }
                        });
                builder.setNegativeButton("取消", null);
                builder.create().show();
            } else  if (lastPressBtnId == R.id.show_ecg) {
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                dialogBuilder.setPositiveButton("打印",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                printTable(item, lastPressBtnId);
                            }
                        });
                dialogBuilder.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                dialogBuilder.setNeutralButton("打印（带结论）",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                printECGTableWithResult(item);
                            }
                        });
                dialogBuilder.setNegativeButton("修改结论",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //根据心电图数据时间time，修改结论并保存
                                editECGResult(item[1], item[0]);
                            }
                        });
                dialogBuilder.setTitle("提示").setMessage("是否连接打印机打印用户测量记录？");
                AlertDialog dialog = dialogBuilder.create();
                dialog.show();
            }
        }
    };

    private void editECGResult(String result, String time) {
        if (result.startsWith("结论：") || result.startsWith("结论:")) {
            result = result.substring(3);
        } else if (result.startsWith("结论")) {
            result = result.substring(2);
        } else if (result.startsWith(":") || result.startsWith("：")) {
            result = result.substring(1);
        }
        showEditEcgResultDialog(result, time);
    }

    private void showEditEcgResultDialog(String result, final String time) {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                LocalRecord.this);
        LayoutInflater inflater = (LayoutInflater) LocalRecord.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout tl = (LinearLayout) inflater.inflate(
                R.layout.activity_tiwen_dialog_chancedevice, null);
        final ListView lv_btdevice_lists = (ListView) tl
                .findViewById(R.id.lv_btdevice_lists);
        final LinearLayout ll_password = (LinearLayout) tl
                .findViewById(R.id.ll_tiwen_password);
        final EditText et_result = (EditText) ll_password
                .findViewById(R.id.et_tiwen_password);
        final TextView tv_pleaseInputPWD = (TextView) ll_password
                .findViewById(R.id.tv_tiwen_password_pleaseInputPWD);
        tv_pleaseInputPWD.setText("结论");
        ll_password.setVisibility(View.VISIBLE);
        lv_btdevice_lists.setVisibility(View.GONE);
        et_result.setText(result);
        et_result.setInputType(InputType.TYPE_CLASS_TEXT);
        et_result.setMaxLines(5);
        builder.setView(tl);
        builder.setTitle("请修改心电结论：");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String result_edited = et_result.getText().toString();
                xindian queryXd = new xindian(time);
                List<Object> xds = (List<Object>) DBService.queryByKey(queryXd);
                if (xds != null && xds.size() == 1) {
                    xindian xd = (xindian) xds.get(0);
                    xd.setRhythm(result_edited);
                    boolean b = DBService.add(xd);
                    if (b) {
                        ToastTool.showLong(context, "修改心电结论成功！");
                    }
                    getAndSetData("xindian");
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }


    /**
     * 打印心电图的报告带结论
     */
    private void printECGTableWithResult(final String[] line) {
        new BackGroundThread(new BackGroundThread.BackGroundTask() {
            @Override
            public void process() {
                // 获取照片的路径，转化为bitmap然后，在bitmap上打印
                String picPath = line[3];
                String result = line[1];
                if (result.startsWith("结论:") || result.startsWith("结论：")) {
                    result = result.substring(3);
                } else if (result.startsWith("结论")) {
                    result = result.substring(2);
                }
                String resultPicPath = FileSaveUtilecg2.saveECGResultPNG(picPath, result);
                File file = new File(resultPicPath);
                if (!file.exists()) {
                    return;
                }
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                // intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                intent.setDataAndType(Uri.fromFile(file), "image/*");
                context.startActivity(intent);
            }
        }).start();
    }

    private void printTable(final String[] line, int btnId) {
        switch (btnId) {
            case R.id.show_hebingPrint:
                // print_hebing();
                break;
            case R.id.show_bp:
                break;
            case R.id.show_urine:
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        printNiaoye(line);
                    }
                }).start();
                break;
            case R.id.show_bo:
                break;
            case R.id.show_temp:
                break;
            case R.id.show_glu:
                break;
            case R.id.show_ecg:
                // 照片地址。
                String picPath = line[3];
                File file = new File(picPath);
                if (!file.exists()) {
                    return;
                }
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                // intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                intent.setDataAndType(Uri.fromFile(file), "image/*");
                context.startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void print_hebing() {
        boolean hasData = false;
        niaoye niaoyeBean = new niaoye();
        niaoyeBean.setIdCard(BaseActivity.getIdCard());
        String niaoye_Time = "";
        List<niaoye> niaoyes = (List<niaoye>) DBService
                .queryByIdCard(niaoyeBean);
        String glu = "";
        String leu = "";
        String bld = "";
        String ph = "";
        String pro = "";
        String ubg = "";
        String nit = "";
        String sg = "";
        String ket = "";
        String bil = "";
        String vc = "";
        if (niaoyes != null && niaoyes.size() > 0) {
            niaoye bean = niaoyes.get(niaoyes.size() - 1);
            niaoye_Time = bean.getTime();// 测量时间
            glu = bean.getGlu();
            leu = bean.getLeu();
            bld = bean.getBld();
            ph = bean.getPh();
            pro = bean.getPro();
            ubg = bean.getUbg();
            nit = bean.getNit();
            sg = bean.getSg();
            ket = bean.getKet();
            bil = bean.getBil();
            vc = bean.getVc();
            hasData = true;
        }
        String name = BaseActivity.getName();
        String sex = "";
        String idCard = BaseActivity.getIdCard();
        String sexCode = BaseActivity.getHealthRecord().getSexCode();
        if (sexCode.equals("1")) {
            sex = "男";
        } else if (sexCode.equals("2")) {
            sex = "女";
        }
        int age = Tools.getYearoldByIdcard(idCard);
        String yearsOld = age == 0 ? "" : age + "";
        // 血糖
        xuetang xuetangBean = new xuetang();
        xuetangBean.setIdCard(BaseActivity.getIdCard());
        List<xuetang> xuetangs = (List<xuetang>) DBService
                .queryByIdCard(xuetangBean);
        String niaoyeDate = "";
        System.out.println("尿液的时间是：" + niaoyeDate);
        String glu_xuetangyi = "";
        String glu_time = "";
        String glu_eat = "";
        if (xuetangs != null && xuetangs.size() > 0) {
            hasData = true;
            // for (int i = 0; i < xuetangs.size(); i++) {
            xuetang bean = xuetangs.get(xuetangs.size() - 1);
            String xuetang_time = bean.getTime();
            // 如果是当天的时间，就循环到最新的一条。
            // if (xuetang_time.contains(niaoyeTime)) {
            glu_xuetangyi = bean.getGlu();
            glu_time = bean.getTime();
            xuetang_time = glu_time;
            glu_eat = bean.getBeforeafter();
            // }
            // }
        }
        // 血压
        xueya xueyaBean = new xueya();
        xueyaBean.setIdCard(BaseActivity.getIdCard());
        List<xueya> xueyas = (List<xueya>) DBService.queryByIdCard(xueyaBean);
        String dbp = "";
        String sbp = "";
        String pulse = "";
        String xueyaTime = "";
        String xueyaHand = "";
        if (xueyas != null && xueyas.size() > 0) {
            hasData = true;
            // for (int i = 0; i < xueyas.size(); i++) {
            xueya bean = xueyas.get(xueyas.size() - 1);
            String t = bean.getTime();
            // if (t.contains(niaoyeTime)) {
            dbp = bean.getDbp();
            sbp = bean.getSbp();
            pulse = bean.getPulse();
            xueyaTime = bean.getTime();
            niaoye_Time = xueyaTime;
            xueyaHand = bean.getHand();
            // }
            // }
        }
        // 体温
        String temp = "";
        String temp_time = "";
        tiwen tiwenBean = new tiwen();
        tiwenBean.setIdCard(BaseActivity.getIdCard());
        List<tiwen> tiwens = (List<tiwen>) DBService.queryByIdCard(tiwenBean);
        if (tiwens != null && tiwens.size() > 0) {
            hasData = true;
            tiwen bean = tiwens.get(tiwens.size() - 1);
            temp = bean.getTemp();
            temp_time = bean.getTime();
            niaoye_Time = temp_time;
        }
        if (niaoye_Time.length() >= 10) {
            niaoyeDate = niaoye_Time.substring(0, 10).replace("/", "-");
        }
        if (!hasData) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastTool.showShort(context, "没有合并的数据，请测量后再打印！");
                }
            });
        } else {
            // FileSaveUtil.saveNiaoye_Xueya_XuetangPdf(context,
            // FileSaveUtil.getSDCardPath() + "/" + name + "/",
            // niaoye_Time.replace("/", "-").replace(" ", "") + ".doc",
            // name, sex, yearsOld, niaoye_Time, glu, leu, bld, ph, pro,
            // ubg, nit, sg, ket, bil, vc, sbp, dbp, pulse, xueyaTime,
            // glu_xuetangyi, glu_time, temp, temp_time);
            String pngPath = FileSaveUtil.getPrintPath_CLJL()
                    + BaseActivity.getHealthRecord().getPersonName() + "/";
            String pngFileName = "hebing.png";
            String hospitalName = SharedpreferenceUtil.getHospitalName(context,
                    "");
            boolean saveOk = FileSaveUtil.saveNiaoye_Xueya_XuetangBitmap(
                    context, pngPath, pngFileName, BaseActivity.getIdCard(),
                    hospitalName, name, sex, yearsOld, niaoye_Time, glu, leu,
                    bld, ph, pro, ubg, nit, sg, ket, bil, vc, sbp, dbp, pulse,
                    xueyaTime, xueyaHand, glu_xuetangyi, glu_time, glu_eat,
                    temp, temp_time);
            if (saveOk) {
                File file = new File(pngPath, pngFileName);
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setDataAndType(Uri.fromFile(file), "image/*");
                context.startActivity(intent);
            } else {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        ToastTool.showShort(context, "合并打印失败");
                    }
                });
            }
        }
    }

    private void printNiaoye(String[] line) {
        if (line.length == 14) {
            String time = line[0];
            String glu = line[3];
            String leu = line[4];
            String bld = line[5];
            String ph = line[6];
            String pro = line[7];
            String ubg = line[8];
            String nit = line[9];
            String sg = line[10];
            String ket = line[11];
            String bil = line[12];
            String vc = line[13];
            String name = BaseActivity.getName();
            String sex = "";
            String idCard = BaseActivity.getIdCard();
            String sexCode = BaseActivity.getHealthRecord().getSexCode();
            if (sexCode.equals("1")) {
                sex = "男";
            } else if (sexCode.equals("2")) {
                sex = "女";
            }
            int age = Tools.getYearoldByIdcard(idCard);
            String yearsOld = age == 0 ? "" : age + "";
            // new Thread(new Runnable() {
            //
            // @Override
            // public void run() {
            // FileSaveUtil.saveNiaoyePdf(context, FileSaveUtil.getSDCardPath()
            // + "/" + name + "/", time.replace("/", "-").replace(" ", "")
            // + ".pdf", name, sex, yearsOld, time, glu, leu, bld, ph,
            // pro, ubg, nit, sg, ket, bil, vc);
            // FileSaveUtil.saveNiaoyePdf(context, FileSaveUtil.getSDCardPath()
            // + "/" + name + "/", "xxx.pdf", name, sex, yearsOld, time,
            // glu, leu, bld, ph, pro, ubg, nit, sg, ket, bil, vc);
            String hospitalName = SharedpreferenceUtil.getHospitalName(context,
                    "");
            String bitmapPath = FileSaveUtil.getSDCardPath() + "/" + name;
            String bitmapName = "niaoye.png";
            boolean saveOK = FileSaveUtil.saveNiaoyeBitmap(context, bitmapPath,
                    bitmapName, idCard, hospitalName, name, sex, yearsOld,
                    time, glu, leu, bld, ph, pro, ubg, nit, sg, ket, bil, vc);
            System.out.println("文件保存结果：" + saveOK);
            if (saveOK) {
                File file = new File(bitmapPath, bitmapName);
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setDataAndType(Uri.fromFile(file), "image/*");
                context.startActivity(intent);
            } else {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        ToastTool.showShort(context, "尿液记录打印失败");
                    }
                });
            }
            // }
            // }).start();
        }
    }

    private void deleteRecordByTime(String time, int btn_id) {
        switch (btn_id) {
            case R.id.show_bp:
                xueya xueya = new xueya();
                xueya.setTime(time);
                DBService.delete(xueya);
                getAndSetData("xueya");
                break;
            case R.id.show_urine:
                niaoye ny = new niaoye();
                ny.setTime(time);
                DBService.delete(ny);
                getAndSetData("niaoye");
                break;
            case R.id.show_bo:
                xueyang xy = new xueyang();
                xy.setTime(time);
                DBService.delete(xy);
                getAndSetData("xueyang");
                break;
            case R.id.show_temp:
                tiwen tw = new tiwen();
                tw.setTime(time);
                DBService.delete(tw);
                getAndSetData("tiwen");
                break;
            case R.id.show_glu:
                xuetang xt = new xuetang();
                xt.setTime(time);
                DBService.delete(xt);
                getAndSetData("xuetang");
                break;
            case R.id.show_xuezhi:
                xuezhi xuezhi = new xuezhi();
                xuezhi.setTime(time);
                DBService.delete(xuezhi);
                getAndSetData("xuezhi");
                break;
            case R.id.show_ecg:
                xindian xindian = new xindian();
                xindian.setTime(time);
                DBService.delete(xindian);
                getAndSetData("xindian");
                break;
            case R.id.latest_measure_btn_uploadall:
                break;
            default:
                break;
        }
    }

    public void printHebing(View view) {
        int id = view.getId();
        if (lastPressBtnId == id)// 当前选中的id
            setButtonState(id);
        lastPressBtnId = id;
        switchSelect(lastPressBtnId);
    }

    private void switchSelect(int id) {
        switch (id) {
            case R.id.show_hebingPrint:
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        print_hebing();
                        // FileSaveUtil.pdf2png("", "");
                        // FileSaveUtil.testpdf(context);
                    }
                }).start();
                break;
            case R.id.show_bp:
                super.setTitleContent("【血压记录】");
                getAndSetData("xueya");
                break;
            case R.id.show_urine:
                super.setTitleContent("【尿液记录】");
                getAndSetData("niaoye");
                break;
            case R.id.show_bo:
                super.setTitleContent("【血氧记录】");
                getAndSetData("xueyang");
                break;
            case R.id.show_temp:
                super.setTitleContent("【体温记录】");
                getAndSetData("tiwen");
                break;
            case R.id.show_glu:
                super.setTitleContent("【血糖记录】");
                getAndSetData("xuetang");
                break;
            case R.id.show_xuezhi:
                super.setTitleContent("【血脂记录】");
                getAndSetData("xuezhi");
                break;
            case R.id.show_ecg:
                super.setTitleContent("【心电记录】");
                getAndSetData("xindian");
                updataEcgDatas();
                break;
            case R.id.latest_measure_btn_uploadall:
                break;
            default:
                break;
        }
    }

    /***
     *
     * @param dataName
     */
    @SuppressWarnings("unchecked")
    private void getAndSetData(String dataName) {
        List<String[]> lists = new ArrayList<String[]>();
        switch (dataName) {
            case "xueya":
                xueya xueyaBean = new xueya();
                xueyaBean.setIdCard(BaseActivity.getIdCard());
                List<xueya> xueyas = (List<xueya>) DBService
                        .queryByIdCard(xueyaBean);
                for (int i = 0; i < xueyas.size(); i++) {
                    xueya bean = xueyas.get(i);
                    String[] line = new String[5];
                    line[0] = bean.getTime();// 测量时间
//				line[0] = bean.getTime().substring(0,10)+"\n"+bean.getTime().substring(11,bean.getTime().length());
                    String dbp = bean.getDbp();
                    String sbp = bean.getSbp();
                    String pulse = bean.getPulse();
                    String hand = bean.getHand();
                    if ("右".equals(hand)) {
                        hand = "右臂";
                    } else {
                        hand = "左臂";
                    }
                    String line1 = "测量位置:" + hand + "\n" + "舒张压：" + dbp + "\n"
                            + "收缩压：" + sbp + "\n" + "脉率：" + pulse;
                    line[1] = line1;
                    line[2] = "已保存";
                    lists.add(line);
                }
                break;
            case "xueyang":
                xueyang xueyangBean = new xueyang();
                xueyangBean.setIdCard(BaseActivity.getIdCard());
                List<xueyang> xueyangs = (List<xueyang>) DBService
                        .queryByIdCard(xueyangBean);
                for (int i = 0; i < xueyangs.size(); i++) {
                    xueyang bean = xueyangs.get(i);
                    String[] line = new String[5];
                    line[0] = bean.getTime();// 测量时间
                    String bo = bean.getBp();
                    String line1 = "血氧值：" + bo;
                    line[1] = line1;
                    line[2] = "已保存";
                    lists.add(line);
                }
                break;
            case "xuezhi":
                xuezhi xuezhiBean = new xuezhi();
                xuezhiBean.setIdCard(BaseActivity.getIdCard());
                List<xuezhi> xuezhis = (List<xuezhi>) DBService
                        .queryByIdCard(xuezhiBean);
                for (int i = 0; i < xuezhis.size(); i++) {
                    xuezhi bean = xuezhis.get(i);
                    String[] line = new String[5];
                    line[0] = bean.getTime();// 测量时间
                    String chol = bean.getChol();
                    String trig = bean.getTrig();
                    String hdl = bean.getHdlchol();
                    String ldl = bean.getCalcldl();
                    String line1 = "总胆固醇：" + chol + "\n" + "甘油三酯：" + trig + "\n"
                            + "HDL：" + hdl + "\n" + "LDL：" + ldl;
                    line[1] = line1;
                    line[2] = "已保存";
                    lists.add(line);
                }
                break;
            case "tiwen":
                tiwen tiwenBean = new tiwen();
                tiwenBean.setIdCard(BaseActivity.getIdCard());
                List<tiwen> tiwens = (List<tiwen>) DBService
                        .queryByIdCard(tiwenBean);
                for (int i = 0; i < tiwens.size(); i++) {
                    tiwen bean = tiwens.get(i);
                    String[] line = new String[5];
                    line[0] = bean.getTime();// 测量时间
                    String temp = bean.getTemp();
                    String line1 = "体温：" + temp;
                    line[1] = line1;
                    line[2] = "已保存";
                    lists.add(line);
                }
                break;
            case "xuetang":
                xuetang xuetangBean = new xuetang();
                xuetangBean.setIdCard(BaseActivity.getIdCard());
                List<xuetang> xuetangs = (List<xuetang>) DBService
                        .queryByIdCard(xuetangBean);
                for (int i = 0; i < xuetangs.size(); i++) {
                    xuetang bean = xuetangs.get(i);
                    String[] line = new String[5];
                    line[0] = bean.getTime();// 测量时间
                    String glu = bean.getGlu();
                    String ba = bean.getBeforeafter();
                    if ("前".equals(ba)) {
                        ba = "测量时间：餐前\n";
                    } else {
                        ba = "测量时间：餐后\n";
                    }
                    String line1 = ba + "血糖值：" + glu;
                    line[1] = line1;
                    line[2] = "已保存";
                    lists.add(line);
                }
                break;
            case "niaoye":
                niaoye niaoyeBean = new niaoye();
                niaoyeBean.setIdCard(BaseActivity.getIdCard());
                List<niaoye> niaoyes = (List<niaoye>) DBService
                        .queryByIdCard(niaoyeBean);
                for (int i = 0; i < niaoyes.size(); i++) {
                    niaoye bean = niaoyes.get(i);
                    String[] line = new String[14];
                    line[0] = bean.getTime();// 测量时间
                    String glu = bean.getGlu();
                    String leu = bean.getLeu();
                    String bld = bean.getBld();
                    String ph = bean.getPh();
                    String pro = bean.getPro();
                    String ubg = bean.getUbg();
                    String nit = bean.getNit();
                    String sg = bean.getSg();
                    String ket = bean.getKet();
                    String bil = bean.getBil();
                    String vc = bean.getVc();
                    String line1 = "glu：" + glu + "\t" + "leu：" + leu + "\t"
                            + "bld：" + bld + "\t" + "ph：" + ph + "\t" + "pro："
                            + pro + "\t" + "ubg：" + ubg + "\t" + "" + "\n" + "nit："
                            + nit + "\t" + "sg：" + sg + "\t" + "ket：" + ket + "\t"
                            + "bil：" + bil + "\t" + "vc：" + vc + "\t";
                    line[1] = line1;
                    line[2] = "已保存";
                    line[3] = glu;
                    line[4] = leu;
                    line[5] = bld;
                    line[6] = ph;
                    line[7] = pro;
                    line[8] = ubg;
                    line[9] = nit;
                    line[10] = sg;
                    line[11] = ket;
                    line[12] = bil;
                    line[13] = vc;
                    lists.add(line);
                }
                break;
            case "xindian":
                xindian xindianBean = new xindian();
                xindianBean.setIdCard(BaseActivity.getIdCard());
                List<xindian> xindians = (List<xindian>) DBService
                        .queryByIdCard(xindianBean);
                for (int i = 0; i < xindians.size(); i++) {
                    xindian bean = xindians.get(i);
                    String[] line = new String[5];
                    line[0] = bean.getTime();// 测量时间
                    String rhythm = bean.getRhythm();
                    String picPath = bean.getPicPath();
                    System.out.println("心电图片位置：" + picPath);
                    String line1 = "结论：" + rhythm;
                    System.out.println("遍历的结论数据是：时间：" + line[0] + ",结论是：" + rhythm);
                    line[1] = line1;
                    line[2] = "已保存";
                    line[3] = picPath;
                    lists.add(line);
                }
                break;
            default:
                break;
        }
        updateData(lists);
    }

    // private static final String[] URINE_CLOUMS = { Tables.LEU, Tables.BLD,
    // Tables.PH, Tables.PRO, Tables.PRO, Tables.UBG, Tables.NIT,
    // Tables.SG, Tables.KET, Tables.BIL, Tables.GLU, Tables.VC };

    /***
     * 0:时间 1：数据内容2：
     */
    private void updataBpDatas() {
    }

    /***
     * 0:时间 1：数据内容2：状态 3:图片地址。4.表名。5上传的路径。
     */
    private void updataEcgDatas() {
    }

    /**
     * 提醒更新数据
     *
     * @param result
     */
    private void updateData(List<String[]> result) {
        datas.clear();
        // datas.add(title);
        datas.addAll(result);
        mAdapter.notifyDataSetChanged();
    }

    /***
     * 设置button的选中效果
     *
     * @param id
     */
    private void setButtonState(int id) {
        for (int each : ids) {
            if (each == id)
                findViewById(each).setSelected(true);
            else
                findViewById(each).setSelected(false);
        }
    }

}
